<template>
  <div class="app-container">
    <el-form inline>
      <el-form-item>
        <el-input v-model="searchObj.username" placeholder="用户名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="getTabledata" >查询</el-button>
        <el-button type="default" @click="clearSearch" >清空</el-button>
      </el-form-item>
    </el-form>
    <div style="margin-bottom: 20px;">
      <el-button type="primary" @click="dialogUserVisible=true" >添  加</el-button>
      <el-button type="danger" @click="revomveUsers" :disabled="selectedIds.length===0"> 批量删除</el-button>
    </div>
    <!-- table表格 -->
    <el-table border stripe :data="userList" v-loading="listLoading" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" width="80" align="center" label="序号"></el-table-column>
      <el-table-column prop="username" label="用户名" width="150" />
      <el-table-column prop="nickName" label="用户昵称" />
      <el-table-column prop="roleName" label="权限列表" />
      <el-table-column prop="gmtCreate" label="创建时间" width="180"/>
      <el-table-column prop="gmtModified" label="更新时间" width="180"/>
      <el-table-column label="操作" width="230" align="center">
        <template slot-scope="{row}">        
          <FengButton type="info" size="mini" icon="el-icon-user-solid" title="分配角色" @click="editUserRole(row)"/>
          <FengButton type="primary" size="mini" icon="el-icon-edit" title="修改用户" @click="editUserInfo(row)"/>
          <el-popconfirm :title="`确定删除 ${row.username} 吗?`" @onConfirm="removeUser(row.id)">
            <FengButton style="margin-left:10px" slot="reference" type="danger" size="mini" icon="el-icon-delete"  title="删除用户"/>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination :current-page="currentPage" :total="total" :page-size="pageSize" :page-sizes="[3,5,10,20]" style="padding: 20px 0;"
    layout="prev, pager, next, jumper, ->, sizes, total"   @current-change="currentChange"  @size-change="sizeChange"></el-pagination>

    <!-- 新建或修改弹框 -->
    <el-dialog :title="user.id? '修改用户':'添加用户'"  :visible.sync="dialogUserVisible">
      <el-form ref="userForm" :model="user" :rules="userRules" label-width="120px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="user.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input v-model="user.nickName"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!user.id">
          <el-input v-model="user.password"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancleUserInfo">取消</el-button>
        <el-button :loading="listLoading" type="primary" @click="addOrUpadteUser">确定</el-button>
      </div>
    </el-dialog>

    <!-- 设置角色 -->
    <el-dialog title="设置角色" :visible.sync="dialogRoleVisible" :before-close="resetRoleData">
      <el-form label-width="80px">
        <el-form-item label="用户名">
          <el-input disabled :value="user.username"></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="userRoleIds" @change="handleCheckedChange">
            <el-checkbox v-for="role in allRoles" :key="role.id" :label="role.id">{{role.roleName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button :loading="listLoading" type="primary" @click="assignRole">保存</el-button>
        <el-button @click="resetRoleData">取消</el-button>
      </div>
    </el-dialog>


  </div>
</template>
<script>
import cloneDeep from 'lodash/cloneDeep'
export default {
  name: 'AclUserList',
  data(){return{
    searchObj:{
      username:'',
    },
    listLoading: false, // 是否显示列表加载的提示
    currentPage:1,
    total:0,
    pageSize:3,
    userList:[],
    selectedIds:[],
    user:{},
    dialogUserVisible:false,
    //角色对话框
    dialogRoleVisible:false,
    isIndeterminate:false,
    checkAll:false, //是否全选
    userRoleIds:[], //选中的用户角色Id
    allRoles:[], //所有角色

    
    userRules:{
      username:[
        {required:true, message:'用户名为必填项'},
        {min:4, message:'用户名不能小于4位'}
      ],
      password:[
        {required:true, validator: this.validatePassword}
      ]
    }
  }},
  created(){
    this.getTabledata();
  },
  methods:{
    //自定义密码校验
    validatePassword(rule, value, callback){
      if(!value){
        callback('密码必须输入');
      } else if ( value.length < 6){
        callback('密码不能小于6位');
      }else{
        callback();
      }
    },


    //当前页更改后回调
    currentChange(currentPage){
      this.currentPage=currentPage;
      this.getTabledata();
    },
    //显示条数更改后回调
    sizeChange(pageSize){
      this.pageSize=pageSize;
      this.getTabledata();
    },
    //获取列表信息
    async getTabledata(){
      this.listLoading = true;
      const result = await this.$API.user.getPageList(this.currentPage,this.pageSize,this.searchObj);
      this.listLoading = false;
      if(result.code==20000){
        const {items, total} = result.data
        // this.userList = items.filter(item => item.username!=='admin')
        // this.total = total-1
        this.userList = items;
        this.total = total;
        this.selectedIds=[];
      }else{
        
      }

    },
    //清空查询条件
    clearSearch(){
      this.searchObj.username='';
      this.getTabledata();
    },

    //删除用户信息
    removeUser(userId){
      this.$confirm("确定删除吗?").then(async () =>{
        const result= await this.$API.user.removeById(userId);
        this.$message.success('删除成功');
        if(this.userList.length===1){
          this.currentPage-=1;
        }
        this.getTabledata();
      }).catch( () =>{
        this.$message.info('取消删除')
      })
    },
    //批量删除
    revomveUsers(){     
      this.$confirm("确定删除吗?").then(async () =>{
        const result=await this.$API.user.removeUsers(this.selectedIds)
        if(result.code==200){
          this.$message.success('删除成功');
          this.getTabledata();
        }
      }).catch(()=>{
        this.$message.info('取消删除')
      })

    },


    // 列表选中状态发生改变的监听回调
    handleSelectionChange(selection){
      this.selectedIds = selection.map(item => item.id)
    },

    //修改用户信息-回调
    editUserInfo(row){
      this.user=cloneDeep(row); //深度拷贝
      this.dialogUserVisible=true;
    },
    //取消
    cancleUserInfo(){
      this.user={};
      this.dialogUserVisible=false;
       //this.$refs.userForm.$resetFields();
       // this.userRules.$reset();
    },
    //添加或修改用户信息
    addOrUpadteUser(){
      this.$refs.userForm.validate(val =>{
        if(val){
          this.listLoading = true;
          this.$API.user[this.user.id ? 'update' : 'add'](this.user).then((result) => {           
            this.$message.success('保存成功!');
            this.listLoading = false;
            this.getTabledata();
            this.user={};
            this.dialogUserVisible = false
          }).catch(()=>{
            this.listLoading = false;
            this.dialogUserVisible = false
          })
        }
      })     
    },

    //显示用户角色界面
    editUserRole(row){
      this.user=row;
      this.dialogRoleVisible=true;
      this.getRoles();
    },


    //关闭Role对话框
    resetRoleData(){
      this.user={};
      this.dialogRoleVisible = false
      this.allRoles = []
      this.userRoleIds = []
      this.isIndeterminate = false
      this.checkAll = false

    },
    //全选勾选状态发生改变时监听--角色
    handleCheckAllChange(val){
      this.userRoleIds= val ? this.allRoles.map(r=> r.id) :[];
      this.isIndeterminate=false;
    },
    //获取所有用户角色
    async getRoles(){
      const result= await this.$API.user.getRoles(this.user.id)
      const {allRolesList, assignRoles} = result.data
      this.allRoles=allRolesList;
      this.userRoleIds= assignRoles.map(r=>r.id);
      this.checkAll= allRolesList.length===assignRoles.length;
      this.isIndeterminate = assignRoles.length>0 && assignRoles.length<allRolesList.length

    },
    //用户分配的角色更改时
    handleCheckedChange(val){
      const {userRoleIds, allRoles} = this
      this.checkAll = userRoleIds.length === allRoles.length && allRoles.length>0
      this.isIndeterminate = userRoleIds.length>0 && userRoleIds.length<allRoles.length
    },
    //保存用户分配的角色
   async assignRole(){
      const roleIds = this.userRoleIds.join(',')
      this.listLoading = true;
      const result = await this.$API.user.assignRoles(this.user.id, roleIds);
      this.listLoading = false
      this.$message.success(result.message || '分配角色成功')
      this.resetRoleData();
      this.getTabledata();
      if (this.$store.getters.name===this.user.username) {
        window.location.reload()
      }

    },

  },
}
</script>